import hljs from 'highlight.js'
import style from './index.module.scss'
import 'highlight.js/styles/atom-one-dark.css'
import markdownItTocAndAnchor from 'markdown-it-toc-and-anchor'
const Clipboard = require('@/utils/clipboard')
const ClipboardJS = Clipboard.default 
const emoji = require('markdown-it-emoji')
const ids: string[] = []
let idIndex = 0
function getId(val: any) {
  const id = `copy${idIndex++}`
  const code = val.code.replace(/"/g,'^*_')
  const text = `id="${id}" data-clipboard-text="${code}"`
  ids.push(id)
  return text
}
const mdParser = require('markdown-it')({
  typographer: true,
  highlight: function (str: any, lang: any) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return `<pre class="hljs"><code>${
          hljs.highlight(lang, str, true).value
        }</code><g ${getId(hljs.highlight(lang, str, true))} >copy</g></pre>`
      } catch (__) {}
    }
  },
})
  .use(emoji)
  .use(markdownItTocAndAnchor, { anchorLink: false })
// 劫持 markdown-it的render方法 使得能拿到渲染后的dom,执行复制操作
mdParser.renders = function (...arg: any) {
  setTimeout(() => {
    for (const el of ids) {
      new ClipboardJS('#' + el).on('success', (e: any) => {
        const domElement = document.querySelector('#' + el)
        ;(domElement as HTMLDivElement).innerHTML = 'copy success!'
        setTimeout(() => {
          ;(domElement as HTMLDivElement).innerHTML = 'copy'
        }, 500)
      })
    }
  }, 0)
  return mdParser.render.apply(this, arg)
}

/* 添加a标签跳转新页面 */
mdParser.renderer.rules.link_open = function (
  tokens: any,
  idx: any,
  options: any,
  _env: any,
  self: any
) {
  // 如果你确认其他的插件不能添加 `target` - 放弃以下检查：
  let aIndex = tokens[idx].attrIndex('target')
  if (aIndex < 0) {
    tokens[idx].attrPush(['target', '_blank']) // 添加新属性
  } else {
    tokens[idx].attrs[aIndex][1] = '_blank' // 替换已经存在的属性值
  }

  // 传递 token 到默认的渲染器。
  return self.renderToken(tokens, idx, options)
}
export { style, mdParser }
